package xu.zhi.qing.share.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xu.zhi.qing.common.constant.Configuration;
import xu.zhi.qing.common.entity.ResponseJson;
import xu.zhi.qing.share.dto.ShareConditionDto;
import xu.zhi.qing.share.entity.ShareCondition;
import xu.zhi.qing.exception.FileUploadException;
import xu.zhi.qing.exception.HideShareException;
import xu.zhi.qing.exception.ShowShareException;
import xu.zhi.qing.share.dto.ShareAddDto;
import xu.zhi.qing.share.entity.Share;
import xu.zhi.qing.share.entity.ShareImg;
import xu.zhi.qing.share.service.ShareImgService;
import xu.zhi.qing.share.service.ShareService;
import xu.zhi.qing.share.vo.SharePageVo;
import xu.zhi.qing.user.entity.User;
import xu.zhi.qing.utils.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
@RequestMapping("/share")
public class ShareController {

    @Autowired
    private ShareService shareService;
    @Autowired
    private ShareImgService shareImgService;

    /**
     * 发布分享
     * @param dto 分享，表单自动填充了content
     * @param request 文件上传需要
     * @return
     * @throws Exception 文件上传抛出的异常
     */
    @RequestMapping(value = "/releaseShare",method = RequestMethod.POST)
    @ResponseBody
    public ResponseJson releaseShare(@ModelAttribute ShareAddDto dto, HttpServletRequest request, HttpSession session){
    	
    	ResponseJson result=new ResponseJson();
        try {
			//取得当前登录的用户
			User user = (User) request.getSession().getAttribute("loginInfo");
			dto.setUserId(user.getId());
			//默认状态为公开
			if(dto.getIsPublic()==null||dto.getIsPublic().equals("0")){
				dto.setStatus(Share.STATUS_PUBLIC);
			}else {
				dto.setStatus(Share.STATUS_PRIVATE);
			}
			//设置发布时间
			dto.setCreateTime(new Timestamp(new Date().getTime()));
			Share share = dto.copyDto(new Share());
			shareService.save(share);

			List<String> pathList = (List<String>)session.getAttribute("pathList");
			if (pathList!=null&&pathList.size()>0&&dto.getImgCount()==0) {
				//图片上传后，没有发布微博，此时将上传的文件删除
				FileUtil.deletePathList(request);
				
			}else if(pathList!=null&&pathList.size()>0&&pathList.size()!=dto.getImgCount()) {
				//说明上传的数量大于目前数量，则从后面往前取
				for(int i=pathList.size()-1;i>=pathList.size()-dto.getImgCount();i--){
					ShareImg shareImg = new ShareImg();
				    shareImg.setImgPath(pathList.get(i).split("#")[0]);
				    shareImg.setSmallImgPath(pathList.get(i).split("#")[1]);
				    shareImg.setShareId(share.getId());
				    shareImgService.save(shareImg);
				}
				
				//上传完成将缓存清空
				request.setAttribute("pathList", null);
				
			}else if(pathList!=null){
				for (String s : pathList) {
				    ShareImg shareImg = new ShareImg();
				    shareImg.setShareId(share.getId());
				    shareImg.setImgPath(s.split("#")[0]);
				    shareImg.setSmallImgPath(s.split("#")[1]);
				    shareImgService.save(shareImg);
				}
				//上传完成将缓存清空
				request.setAttribute("pathList", null);
			}
			result.setStatus(true);
			result.setMsg("发布分享成功！");
		} catch (Exception e) {
			//有异常也将文件删除
			FileUtil.deletePathList(request);
			e.printStackTrace();
			result.setStatus(false);
			result.setMsg("发布分享失败！");
		}
        return result;
    }
    
    /**
     * session中的pathList格式为 原图路径+'#'+缩略图路径
     * @param session
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartHttpServletRequest request, HttpSession session){
		Map<String, MultipartFile> fileMap = request.getFileMap();
		List<MultipartFile> list = new ArrayList<>(fileMap.values());
		MultipartFile[] files = new MultipartFile[list.size()];
		list.toArray(files);
    	try {
			List<String> pathList = FileUtil.upload(files, new String[]{"jpg","jpeg","png","gif"});
			pathList=FileUtil.createThumbnails(pathList);
			//将路径放入缓存
			List<String> buffer = (List<String>)session.getAttribute("pathList");
			if (buffer==null) {
				buffer= new ArrayList<>();
			}
			if(pathList!=null){
				for (String path : pathList) {
					buffer.add(path);
				}
			}
			session.setAttribute("pathList", buffer);
			return "true";
		} catch (FileUploadException e) {
			e.printStackTrace();
			return "false";
		}
    }

    /**
     * 显示分页分享列表
     * @param request 请求
     * @return
     */
    @ResponseBody
    @RequestMapping("/listShare")
    public SharePageVo listShare(ShareConditionDto dto, HttpServletRequest request) {
        //参数验证
        if (dto.getPageNo() == null) {
            //默认显示第一页
            dto.setPageNo(1);
        }
        if (dto.getPageSize() == null) {
            //默认页大小
            dto.setPageSize(Configuration.SHARE_PAGE_SIZE);
        }
        //当前用户
        User currentUser = (User) request.getSession().getAttribute("loginInfo");
        //封装要传递的参数
        ShareCondition shareCondition = new ShareCondition();
        shareCondition = dto.copyDto(shareCondition);
        shareCondition.setCurrentUserId(currentUser.getId());
        Integer shareType = shareCondition.getShareType();
        SharePageVo respone = null;
        if (shareType == null || shareType.equals(Configuration.SHARE_TYPE_DEFAULT)) {
            //默认的分享
            respone = shareService.findByPage(shareCondition);
        } else if (shareType.equals(Configuration.SHARE_TYPE_LIKE)) {
            //点赞的分享
            respone = shareService.findByLikeAndPage(shareCondition);
        } else if (shareType.equals(Configuration.SHARE_TYPE_COMMENT)) {
            //评论的分享
            respone = shareService.findByCommentAndPage(shareCondition);
        } else if (shareType.equals(Configuration.SHARE_TYPE_COLLECT)) {
            //收藏的分享
            respone = shareService.findByCollectAndPage(shareCondition);
        } else if (shareType.equals(Configuration.SHARE_TYPE_LIKE_RANKING)) {
            //点赞榜
            respone = shareService.findByLikeRankingAndPage(shareCondition);
        }
        return respone;
    }

    /**
     * 屏蔽分享
     * @param id 被屏蔽的分享id
     * @return
     */
    @RequestMapping("/hideShare")
    @ResponseBody
    public ResponseJson hideShare(Integer id, HttpSession session){
    	ResponseJson result=new ResponseJson();
    	try {
			//1.获取当前用户id
			Integer currentUserId = ((User)session.getAttribute("loginInfo")).getId();
			//2.调用service隐藏share
			shareService.hideShare(currentUserId, id);
			result.setStatus(true);
			result.setMsg("屏蔽分享成功！");
		} catch (HideShareException e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMsg(e.getMessage());
		}
    	return result;
    }

    /**
     * 取消屏蔽分享
     * @param id 分享id
     * @return
     */
    @RequestMapping("/showShare")
    @ResponseBody
    public ResponseJson showShare(Integer id, HttpSession session){
    	ResponseJson result=new ResponseJson();
    	try {
			//1.获取当前用户id
			Integer currentUserId = ((User)session.getAttribute("loginInfo")).getId();
			//2.调用service隐藏share
			shareService.showShare(currentUserId, id);
			result.setStatus(true);
			result.setMsg("取消屏蔽分享成功！");
		} catch (ShowShareException e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMsg(e.getMessage());
		}
    	return result;
    }

	/**
	 * 删除分享
	 * @param share 分享(id)
	 * @return
	 */
	@RequestMapping("/deleteShare")
	@ResponseBody
	public ResponseJson deleteShare(Share share) {
		ResponseJson result = new ResponseJson();
		shareService.deleteShare(share);
		result.setStatus(true);
		return result;
	}
}
